package com.ys.peony.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.megvii.idcardquality.IDCardQualityLicenseManager;
import com.megvii.licensemanager.Manager;
import com.megvii.livenessdetection.LivenessLicenseManager;
import com.megvii.livenesslib.util.ConUtil;
import com.ys.peony.R;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.enums.SwipeDirect;
import com.ys.peony.ui.fragment.FaceFragment;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * describe:证件审核
 * author:yukang
 */
public class DocumentsReviewActivity extends BaseActivity {

    public final static int MAIN_TYPE = 1;//自己身份识别标记
    public final static int OTHER_TYPE = 2;//配偶身份识别标记

    private final static int AUTHOR_SUCCESS = 1;
    private final static int AUTHOR_FAIL = 2;
    @BindView(R.id.titleback)
    ImageView titleback;
    @BindView(R.id.select_sort)
    RadioGroup select_sort;
    @BindView(R.id.face_main)
    RadioButton face_main;
    @BindView(R.id.face_other)
    RadioButton face_other;
    @BindView(R.id.id_viewpager)
    ViewPager mViewPager;


    private List<Fragment> mList = new ArrayList<>();
    private boolean authorize;//是否授权成功

    private boolean uploadSuccess = false;
    private boolean isMainFinish = false; //判断主借人人脸识别是否已经完成
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AUTHOR_SUCCESS:
                    authorize = true;
                    break;
                case AUTHOR_FAIL:
                    ToastUtils.showToast("联网授权失败,请退出重试");
                    authorize = false;
                    break;
            }

        }
    };

    @Override
    protected int getContentResId() {
        return R.layout.activity_documents_review;
    }

    @Override
    protected void initView() {
        identifyFace();
        initData();
        initListener();
        initAdapter();
    }

    /**
     * 描述：联网授权身份识别相关
     */
    private void identifyFace() {
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                //证件扫描联网授权
                idcardWarranty();
            }
        }).start();
    }

    private void initData() {
        FaceFragment faceMainFragment = new FaceFragment();
        FaceFragment faceOtherFragment = new FaceFragment();
        faceMainFragment.setType(MAIN_TYPE);
        faceOtherFragment.setType(OTHER_TYPE);
        mList.add(faceMainFragment);
        mList.add(faceOtherFragment);
    }

    private void initAdapter() {
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mList.get(position);
            }

            @Override
            public int getCount() {
                return mList.size();
            }
        });
    }


    private void initListener() {
        select_sort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i) {
                    case R.id.face_main:
                        mViewPager.setCurrentItem(0);
                        hideInput();
                        break;
                    case R.id.face_other:
                        mViewPager.setCurrentItem(1);
                        hideInput();
                        break;
                }
            }
        });

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                changeBtn(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        titleback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                backUp();
            }
        });
    }

    private void changeBtn(int position) {
        switch (position) {
            case 0:
                face_main.setChecked(true);
                hideInput();
                break;
            case 1:
                face_other.setChecked(true);
                hideInput();
                break;
        }
    }

    /**
     * describe:证件识别联网授权
     * 联网授权不成功，只有三种原因：
     * 1. 网络连接、有没有安全软件阻止
     * 2. 手机本地时间有问题
     * 3. BundleID是否和faceid官网申请的不一致
     * author:yukang
     */
    private void idcardWarranty() {
        try {
            Manager manager = new Manager(this);
            IDCardQualityLicenseManager idCardLicenseManager = new IDCardQualityLicenseManager(this);
            manager.registerLicenseManager(idCardLicenseManager);
            String faceUUID = ConUtil.getUUIDString(this);
            manager.takeLicenseFromNetwork(faceUUID);
            if (idCardLicenseManager.checkCachedLicense() > 0) {
                faceWarranty();
            } else {
                mHandler.sendEmptyMessage(AUTHOR_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * describe:人脸识别联网授权
     * author:yukang
     */
    private void faceWarranty() {
        Manager manager = new Manager(this);
        LivenessLicenseManager licenseManager = new LivenessLicenseManager(this);
        manager.registerLicenseManager(licenseManager);
        String faceUUID = ConUtil.getUUIDString(this);
        manager.takeLicenseFromNetwork(faceUUID);
        if (licenseManager.checkCachedLicense() > 0) {
            mHandler.sendEmptyMessage(AUTHOR_SUCCESS);
        } else {
            mHandler.sendEmptyMessage(AUTHOR_FAIL);
        }
    }

    public boolean getAuthorResult() {
        return authorize;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    /**
     * describe:返回
     * author:czhang
     * date:2017/6/10 22:50
     */
    private void backUp() {
        Bundle bundle = new Bundle();
        if (isUploadSuccess()) {
            bundle.putInt("requestCode", DaiMianShenListActivity.REQUEST_CODE);
        } else {
            bundle.putInt("requestCode", YSConstant.INVALID);
        }
        skipToTargetPage(DaiMianShenListActivity.class, bundle, SwipeDirect.DIRECT_RIGHT);
    }

    public boolean isMainFinish() {
        return isMainFinish;
    }

    public void setMainFinish(boolean mainFinish) {
        isMainFinish = mainFinish;
    }

    @Override
    public void onBackPressed() {
        backUp();
        super.onBackPressed();
    }

    public boolean isUploadSuccess() {
        return uploadSuccess;
    }

    public void setUploadSuccess(boolean uploadSuccess) {
        this.uploadSuccess = uploadSuccess;
    }


}
